﻿using DocumentFormat.OpenXml.Lite.Core;
using DocumentFormat.OpenXml.Lite.Core.Interfaces;
using DocumentFormat.OpenXml.Lite.Core.Office;
using DocumentFormat.OpenXml.Lite.Helper;
using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.WordprocessingML.Word.ParagraphProperties;
using DocumentFormat.OpenXml.Lite.WordprocessingML.Word.SectionProperties;
using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.WordprocessingML.Word.Base
{
    [XmlRoot("p", Namespace = Constants.WordMain)]
    public class Paragraph : XmlSerializable, IOfficeElement, ISectionPropertyContainer
    {
        [XmlIgnore]
        public Guid DocumentId { get; set; }

        [Optional]
        [XmlElement("pPr", Namespace = Constants.WordMain)]
        public ParagraphProperties Properties { get; set; }

        [Optional]
        [XmlElement("r", Namespace = Constants.WordMain)]
        public XmlList<Run> Runs { get; set; }

        public Paragraph()
        {
            Runs = new XmlList<Run>();
            Runs.Changing += Runs_Changing;

            Properties = new ParagraphProperties();
        }

        #region Methods

        public Run AddRun()
        {
            Run r = new Run();
            r.DocumentId = this.DocumentId;
            Runs.Add(r);
            return r;
        }

        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        /// <param name="element"></param>
        /// <returns>True, if the list not contains element with the same type. 
        /// False otherwise (in this case the content will be override the old one).</returns>
        public bool AddProperty(IParagraphPropElement element)
        {
            if (Properties == null)
            {
                Properties = new ParagraphProperties();
            }

            var obj = Properties.Properties.FirstOrDefault(e => e.GetType() == element.GetType());
            if (obj != null)
            {
                (obj as IRunPropElement).Copy(element);
            }
            else
            {
                Properties.Properties.Add(element);
                return true;
            }

            return false;
        }

        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        /// <param name="element"></param>
        /// <returns>True, if the list not contains element with the same type. 
        /// False otherwise (in this case the content will be override the old one).</returns>
        public bool AddSectionProperty(ISectionPropElement element)
        {
            if (Properties == null)
            {
                Properties = new ParagraphProperties();
            }

            var sp = Properties.Properties.FirstOrDefault(p => p.GetType() == typeof(SectionProperty));
            if (sp == null)
            {
                sp = new SectionProperty();
                Properties.Properties.Add(sp);
            }

            if (element is HeaderReference ||
                 element is FooterReference ||
                 element is PrinterSettings)
            {
                (DocumentManager.Instance.FindDocument(DocumentId) as WordDocument).Document
                    .AddNamespace(Constants.GetDefaultPrefix(Constants.Relationship), Constants.Relationship);
            }

            var obj = (sp as SectionProperty).Elements.FirstOrDefault(e => e.GetType() == element.GetType());
            if (obj != null)
            {
                (obj as ISectionPropElement).Copy(element);
            }
            else
            {
                (sp as SectionProperty).Elements.Add(element);
                return true;
            }

            return false;
        }

        #endregion

        #region Events

        void Runs_Changing(object sender, ListEventArgs<Run> args)
        {
            if (args.Type == ListEventType.Remove)
                return;

            foreach (var r in args.Objects)
            {
                r.DocumentId = this.DocumentId;
            }
        }

        #endregion
    }

    [XmlRoot("pPr", Namespace = Constants.WordMain)]
    public class ParagraphProperties : XmlSerializable
    {
        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        [Optional]
        [XmlElement("", Namespace = Constants.WordMain)]
        public XmlList<IParagraphPropElement> Properties { get; set; }

        public ParagraphProperties()
        {
            Properties = new XmlList<IParagraphPropElement>();
            Properties.Changing += Properties_Changing;
        }

        void Properties_Changing(object sender, ListEventArgs<IParagraphPropElement> args)
        {
            if (args.Type == ListEventType.Remove)
                return;

            foreach (var obj in args.Objects)
            {
                if (obj.GetType().IsInheritedFrom(typeof(IParagraphPropElement)))
                {
                    var element = Properties.FirstOrDefault(e => e.GetType() == obj.GetType());
                    if (obj != null)
                    {
                        throw new OpenXmlException("Element with the same type (" +
                            element.GetType().ToString() + ") already added to list: " + Properties.ToString());
                    }
                }
            }
        }
    }
}
